/*
 * @Author       : wfl
 * @LastEditors: wfl
 * @description  :
 * @updateInfo   :
 * @Date         : 2023-03-21 14:03:51
 * @LastEditTime: 2023-04-14 16:01:31
 */
import fs from 'fs'
import path from 'path'

interface TreeNode {
  value: string
  label: string
  children?: TreeNode[]
}
const DIR_MAIN = 'src/MainApp/views'
const DIR_MICRO = 'src/MicroApp/views'

let _env: any = null
let watcher: fs.FSWatcher | null = null
let watcher2: fs.FSWatcher | null = null

const readPackage = () => {
  const _package = fs.readFileSync('package.json', 'utf-8')
  const dependencies = JSON.parse(_package).dependencies
  const keys = Object.keys(dependencies)
  if (keys.includes('dayjs'))
    console.info('\x1B[33m[Iking-Admin]检测到dayjs, 请替换为import { dayjs } from "iking-utils"\x1B[0m')
  if (keys.includes('loadsh') || keys.includes('lodash-es'))
    console.info('\x1B[33m[Iking-Admin]检测到loadsh(lodash-es), 请替换为import { _ } from "iking-utils"\x1B[0m')
  if (keys.includes('mitt'))
    console.info('\x1B[33m[Iking-Admin]检测到mitt, 请替换为import { ikMitt } from "iking-utils"\x1B[0m')
  if (keys.includes('decimal.js'))
    console.info('\x1B[33m[Iking-Admin]检测到decimal.js, 请替换为import { ikMath } from "iking-utils"\x1B[0m')
}

const replaceDir = (dir: string) => {
  return dir.replace(/\\/g, '/').replace(DIR_MAIN, '').replace(DIR_MICRO, '')
}

const buildTree = (dir: string): TreeNode | null => {
  const stats = fs.statSync(dir)
  if (!stats.isDirectory())
    return null

  const files = fs.readdirSync(dir)
  const tree: TreeNode = {
    value: replaceDir(dir) || 'views',
    label: path.basename(dir)
  }

  files.forEach(file => {
    if (!tree.children)
      tree.children = []

    const filePath = path.join(dir, file)
    const fileStats = fs.statSync(filePath)
    const IS_DIR = fileStats.isDirectory()
    if (IS_DIR) {
      const subtree = buildTree(filePath)
      if (subtree)
        tree.children?.push(subtree)
    }
    else {
      const _dir_ = replaceDir(filePath).substring(1)
      tree.children?.push({
        value: _dir_,
        label: _dir_
      })
    }
  })

  return tree
}

export default function createFolderTree(doenv: any) {
  return {
    name: 'folder-tree-plugin',
    config() {
      createFolder(doenv)
    }
  }
}

export const createFolder = (env: any) => {
  _env = env
  if (_env.VITE_WATCH_FOLDER === 'false')
    return
  console.info('\x1B[33m[Iking Admin]: 构建目录树\x1B[0m')
  const _dir_main = buildTree(DIR_MAIN)
  const _dir_micro = buildTree(DIR_MICRO)
  console.info('\x1B[33m[Iking Admin]: 写入目录树: [ src/assets/json/folder.json ]\x1B[0m')
  fs.writeFileSync('src/assets/json/folder.json', JSON.stringify({
    main: _dir_main,
    micro: _dir_micro
  }))
  console.info('\x1B[33m[Iking Admin]: 写入完成(可在菜单管理页面新增/编辑时在“组件路径”中选择)\x1B[0m')

  if (_env.VITE_WATCH_FOLDER) {
    watcher = fs.watch(DIR_MAIN, () => {
      console.info('\x1B[33m[Iking Admin]: 目录Change, 重新构建\x1B[0m')
      createFolder(_env)
    })
    watcher2 = fs.watch(DIR_MICRO, () => {
      console.info('\x1B[33m[Iking Admin]: 目录Change, 重新构建\x1B[0m')
      createFolder(_env)
    })
  }

  else {
    watcher && watcher.close()
    watcher2 && watcher2.close()
  }
  readPackage()
}
